package com.tanglon.task;

import com.tanglon.domain.dto.ExcelUserDTO;
import com.tanglon.domain.entity.User;

import com.tanglon.service.UserService;
import com.tanglon.utils.BeanCopyUtils;

import java.util.List;
import java.util.concurrent.CountDownLatch;


public class DeadMainThread implements Runnable {

    private final UserService userService;
    private int start;
    private int end;
    private List<ExcelUserDTO> list;
    private CountDownLatch countDownLatch;

    // 新增构造函数，接收UserService
    public DeadMainThread(CountDownLatch countDownLatch, List<ExcelUserDTO> list, int start, int end, UserService userService) {
        this.countDownLatch = countDownLatch;
        this.start = start;
        this.end = end;
        this.list = list;
        this.userService = userService; // 手动传入Spring管理的实例
    }


    @Override
    public void run() {
        try{
            List<ExcelUserDTO> tempList = list.subList(start, end);
            //批量新增
            List<User> userList = BeanCopyUtils.copyBeanList(tempList, User.class);
            userService.saveBatch(userList);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //当一个线程执行完了计数要减一，不然这个线程一直被挂起
            countDownLatch.countDown();
            System.out.println("减一:"+countDownLatch.getCount());
        }
    }
}
